import sensor
import image
import lcd
import time
import image
import struct
from machine import UART
from fpioa_manager import fm
lcd.init()
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)  #灰度图像
sensor.set_framesize(sensor.QVGA)
sensor.run(1)
fm.register(10, fm.fpioa.UART1_TX, force=True) #10为tx接rx
fm.register(9, fm.fpioa.UART1_RX, force=True) #11为rx接tx

sensor.skip_frames(10) # 跳过10帧，使新设置生效
#对绿色色块识别，具体参数调试见下图
#black_threshold   = (10, 0, 0, 8, -5, 8)
#根据自己的需求操作色块对象, 例如将色块对象在图像中用矩形框标识出来

black_threshold   = (91, 255)
#检测窗口

ROI = (0, 100, 320, 20)#窗口1
ROI1 = (0, 140, 320, 20)#窗口1
ROI2 = (0, 180, 320, 20)#窗口1

uart = UART(1, 115200)
uart.init(115200, bits=8, parity=None, stop=1)  # init with given parameters

while True:
    sensor.set_vflip(True)  #垂直翻转
    ix = 0
    iy = 0
    ih = 0


    img=sensor.snapshot()   #拍摄
    img_black = img.binary([black_threshold])   #二值化为黑
    img_black.mean(2)
    img.invert()
    blobs = img.find_blobs([black_threshold],roi = ROI)
    if blobs:
        for b in blobs:
            tmp=img.draw_rectangle(b[0:4])
            tmp=img.draw_cross(b[5], b[6])
            c=img.get_pixel(b[5], b[6])
            ix = b[5]
            print(ix)
    lcd.display(img)
    FH = bytearray([0x2c,0x12,ix, iy,ih,0x5B])
    uart.write(FH)
    time.sleep_ms(100)


#返回图像长宽
    kuan = img.width()
#返回图像的宽度(像素)

    gao = img.height()
    #print(kuan, gao)

#测试成功

#画检测框

    statistics=img.get_statistics(roi=ROI)
    statistics=img.get_statistics(roi=ROI1)
    statistics=img.get_statistics(roi=ROI2)
    img.draw_rectangle(ROI)
    img.draw_rectangle(ROI1)
    img.draw_rectangle(ROI2)


#返回图像的高度(像素)
#返回像素值0
    #img = image.Image(size=(20, 20))
    #print("pixel 0:", img[2], img.get_pixel(150, 125))
    #img[0] = (255, 0, 0)
    #img = img.set_pixel(1, 0, (255, 255, 10))
    #print("after pixel 0 change:", img[0], img[1])


#测试失败

#返回像素值1

    #img = sensor.snapshot()
    #img.get_pixel(10,15)
    #x = img.get_pixel(10,15)         #显示（10，15）像素点rgb值
    #print(x)
    #img.set_pixel(10,10,(255,0,0))     #设置像素点（10，10）为红色

#测试成功


#计算区域内平均lab
    #img = sensor.snapshot()         # Take a picture and return the image.
    #statistics=img.get_statistics(roi=(125,110,58,54))
    #color_l=statistics.l_mode()
    #color_a=statistics.a_mode()
    #color_b=statistics.b_mode()
    #print(color_l,color_a,color_b)

#测试成功

#转为灰度图
    #img = img.to_grayscale(copy=False)
#测试成功






